package com.slipper.codeless.resolve;

import com.slipper.constants.Constants;
import com.slipper.groovy.service.GroovyService;
import com.slipper.util.DateUtil;
import com.slipper.util.Tool;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class SymbolUtil {
    public static String parse(String symbol) {
        if (Tool.isBlank(symbol)) return null;
        if (!symbol.trim().startsWith("${")) return symbol;

        String tplValue = symbol.trim().substring(2, symbol.trim().length() - 1);
        String[] tplValues = tplValue.split("\\.");
        if (tplValues.length < 2) return symbol;

        switch (tplValues[0]) {
            case "user" -> {
                Map<String, Object> userMap = Constants.getCurrentUser().getUser();
                Object value = userMap.get(tplValues[1]);
                return value == null ? null : value.toString();
            }
            case "org" -> {
                Map<String, Object> userMap = Constants.getCurrentUser().getOrg();
                Object value = userMap.get(tplValues[1]);
                return value == null ? null : value.toString();
            }
            case "script" -> {
                Object value = GroovyService.runById(tplValues[1]);
                return value == null ? null : value.toString();
            }
            case "date" -> {
                return switch (tplValues[1]) {
                    case "currYear" -> Calendar.getInstance().get(Calendar.YEAR) + "";
                    case "currMonth" -> (Calendar.getInstance().get(Calendar.MONTH) + 1) + "";
                    case "currDay" -> (Calendar.getInstance().get(Calendar.DAY_OF_MONTH) + 1) + "";
                    case "currDate" -> DateUtil.formatDate(new Date());
                    case "currTime" -> System.currentTimeMillis() + "";
                    default -> null;
                };
            }
            default -> {
                return null;
            }
        }
    }
}
